package cc.autoapi.pucong.auto.flow.provider.api.manager;


import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import cc.autoapi.pucong.auto.flow.core.flow.execNode.entity.api.ApiHandlerMsgDto;
import cc.autoapi.pucong.auto.flow.core.flow.execNode.entity.task.ApiExecResult;
import cc.autoapi.pucong.auto.flow.core.flow.execNode.eventBus.ISubscriberAbstract;
import cc.autoapi.pucong.auto.flow.core.flow.execNode.exec.DataBus;
import cc.autoapi.pucong.auto.flow.core.flow.execNode.selfenum.LogLevelTypeEnum;
import cc.autoapi.pucong.auto.flow.core.flow.execNode.selfenum.MsgTypeEnum;
import cc.autoapi.pucong.auto.flow.core.flow.execNode.selfenum.RunStatusEnum;
import cc.autoapi.pucong.auto.flow.persistence.po.api.ApiInfoPo;
import cc.autoapi.pucong.auto.flow.persistence.po.log.ApiInstancePo;
import cc.autoapi.pucong.auto.flow.persistence.repository.api.ApiInfoService;
import cc.autoapi.pucong.auto.flow.persistence.repository.log.ApiInstanceService;
import cc.autoapi.pucong.auto.flow.provider.log.manager.LogManager;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: cong.pu
 * @create: 2024-10-08 10:02
 **/
@Service
public class ApiHandler extends ISubscriberAbstract<ApiHandlerMsgDto> {


    @Resource
    private ApiInfoService apiInfoService;

    @Resource
    private ApiInstanceService apiInstanceService;

    @Resource
    private LogManager logManager;

    @Override
    public String getMessageType() {
        return MsgTypeEnum.API_MSG.getType();
    }

    @Override
    public void receiveMessage(ApiHandlerMsgDto message) {
        String instanceId = message.getInstanceId();
        String apiId = message.getApiId();
        RunStatusEnum runStatusEnum = message.getRunStatus();
        ApiInstancePo apiInstancePo = null;
        synchronized (this) {
            apiInstancePo = apiInstanceService.getById(instanceId);
            if (apiInstancePo == null) {
                ApiInfoPo byId = apiInfoService.getById(apiId);

                apiInstancePo = new ApiInstancePo();
                apiInstancePo.setUuid(instanceId);
                apiInstancePo.setApiId(apiId);
                apiInstancePo.setExeStatus(3);
                apiInstancePo.setValueJson(byId.getApiJson());
                apiInstancePo.setCreateTime(new Date());
                apiInstanceService.save(apiInstancePo);
            }
        }
        if (runStatusEnum != null) {
            if (runStatusEnum == RunStatusEnum.执行中) {
                Map<String, Object> bodyMap = DataBus.getBodyParamMap(instanceId);
                Map<String, Object> queryMap = DataBus.getQueryParams(instanceId);
                Map<String, String> headerMap = DataBus.getHeaderParamMap(instanceId);
                JSONObject params = new JSONObject();
                params.put("queryMap", queryMap);
                params.put("headerMap", headerMap);
                params.put("bodyMap", bodyMap);

                ApiInstancePo updateId = new ApiInstancePo();
                updateId.setUuid(instanceId);
                updateId.setExeStatus(2);
                updateId.setExeStartTime(new Date());
                apiInstanceService.updateById(updateId);
                // 插入执行日志
                logManager.appendLog(LogLevelTypeEnum.INFO, instanceId, "开始执行");
            } else if (runStatusEnum == RunStatusEnum.执行成功) {
                ApiExecResult apiStatus = DataBus.getApiStatus(instanceId);
                Object data = apiStatus.getData();
                String result = null;
                if (data instanceof List) {
                    result = JSONArray.toJSONString(data);
                } else {
                    result = JSONObject.toJSONString(data);
                }
                ApiInstancePo updateId = new ApiInstancePo();
                updateId.setUuid(instanceId);
                updateId.setExeStatus(1);
                updateId.setExeEndTime(message.getCreateTime());
                updateId.setApiParamsOut(result);
                apiInstanceService.updateById(updateId);
                // 插入执行日志
                logManager.appendLog(LogLevelTypeEnum.INFO, instanceId, "执行成功");
            } else if (runStatusEnum == RunStatusEnum.执行失败) {
                ApiInstancePo updateId = new ApiInstancePo();
                updateId.setUuid(instanceId);
                updateId.setExeStatus(0);
                updateId.setExeEndTime(message.getCreateTime());
                apiInstanceService.updateById(updateId);
                // 插入执行日志
                logManager.appendLog(LogLevelTypeEnum.ERROR, instanceId, "执行失败");
            }
        }
        LogLevelTypeEnum logLevel = message.getLogLevel();
        if (logLevel != null) {
            // 插入执行日志
            logManager.appendLog(logLevel, instanceId, message.getLogContent());
        }
    }
}